import React, {Component} from 'react';
import {Button, Row, Col, Input, Form, Table, Modal, Pagination} from 'antd';
import {ButtonSubmit} from "../components/AddComponent";
import app from '../AppMethod';
import {car} from "../value";
import {Consumer} from "../store";

const FormItem = Form.Item;
const confirm = Modal.confirm;
const pageLength = 10;

class carManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            isAddValid: false,
            data: [],
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            allPage: 0,
            addConfirmLoading: false,
            searchData: {},

        }
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };
    columns = [
        {
            title: '车牌号',
            dataIndex: 'vehicle_num',
        },
        {
            title: '创建时间',
            dataIndex: 'vehicle_createtime'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        <span style={{color: '#f5222d', cursor: 'pointer', marginLeft: '10px'}}
                              onClick={() => this.handleDelete(data.vehicle_id)}>删除</span>
                    </span>
                )
            }
        }
    ];

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => this.handleReset()}
                    >
                    </SearchLists>
                </Row>
                <Row>
                    <ButtonSubmit
                        isVisible={this.state.isAddValid == null ? false : this.state.isAddValid}
                        title="增加车辆" buttonText={'增加'} width="600px"
                        addConfirmLoading={this.state.addConfirmLoading}
                        click={(e) => this.handleCancel(true)}
                        clickOk={(e) => this.handleSubmit(e)}
                        clickCancel={(e) => this.handleCancel(false)}
                    >
                        <Row>
                            <Col offset={1} span={22}>
                                <Form className="login-form">
                                    <FormItem label="车牌号" {...this.formItemLayout}>
                                        {
                                            getFieldDecorator('vehicle_num', {
                                                rules: [{required: true, message: '请输入车牌号'}]
                                            })(
                                                <Input placeholder="请输入"/>
                                            )
                                        }
                                    </FormItem>
                                </Form>
                            </Col>
                        </Row>
                    </ButtonSubmit>
                </Row>
                {/*主体内容*/}
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={record => record.vehicle_id}
                        dataSource={this.state.data}
                        pagination={false}
                        loading={this.state.loading}
                    >
                    </Table>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}
                                    hideOnSinglePage={false}/>
                    </Col>
                </Row>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "车辆管理"});
        this.handleRefresh();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    }

    /**
     * 处理重置事件
     */
    handleReset() {
        this.setState({searchData: {}});
        this.handleRefresh();
    }

    /**
     * 处理刷新事件
     */
    handleRefresh() {
        this.setState({searchData: {}});
        this.handleGetLineList();
    }

    /**
     * 获取车辆列表
     * @param data
     */
    handleGetLineList(data = {page: 1, size: 10}) {
        this.setState({loading: true});
        app.post(car.GET_VEHICLELIST, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let resultData = result.data.dataSet;
                for (let i = 0; i < resultData.length; i++) {
                    resultData[i].vehicle_createtime = app.timeFormat(resultData[i].vehicle_createtime);
                }
                this.setState({data: resultData, loading: false, pagination, allPage});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({loading: false, data: [], pagination, allPage});
                app.alert(result.msg, 'error', 3);
            }
        })
    }

    /**
     * 查询车辆
     * @param value
     */
    handleGetSearch(value) {
        this.setState({
            searchData: value
        });
        let data = {
            vehicle_num: value.vehicle_num,
            page: 1,
            size: this.state.pagination.pageSize || 10
        };
        this.handleGetLineList(data);
    };

    /**
     * 显示和隐藏弹框
     * @param visible
     */
    handleCancel(visible) {
        this.setState({
            isAddValid: visible
        })
    };

    /**
     * 增加车辆
     * @param e
     */
    handleSubmit = (e) => {
        let _this = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log(values);
                app.post(car.ADD_VEHICLE, values).then((result) => {
                    if (result.code === 1) {
                        app.alert('添加成功', 'success', 3);
                        _this.handleCancel(false);
                        _this.handleRefresh();
                    } else {
                        app.alert(result.msg, 'error', 3);
                    }
                })
            }
        })
    };

    /**
     * 删除车辆
     * @param id
     */
    handleDelete(id) {
        const _this = this;
        confirm({
            content: '您确认删除这条路线吗？',
            onOk() {
                app.post(car.DELETE_VEHICLE, {vehicle_id: id}).then((result) => {
                    if (result.code === 1) {
                        app.alert('删除成功', 'success', 3);
                        _this.handleAfterDel();
                    } else {
                        app.alert(result.msg, 'error', 3);
                    }
                })
            },
            onCancel() {

            }
        })
    };

    /**
     * 处理删除后查询车辆列表功能
     */
    handleAfterDel() {
        let data = this.state.searchData;
        data.page = 1;
        data.size = 10;
        this.handleGetLineList(data);
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleGetLineList(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleGetLineList(data);
    };
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Col span={6}>
                            <FormItem label="车牌号" {...this.formItemLayout}>
                                {
                                    getFieldDecorator('vehicle_num')(
                                        <Input type="text" placeholder="请输入"
                                               onPressEnter={() => this.handleOnPressEnter()}/>
                                    )
                                }
                            </FormItem>
                        </Col>
                        <Col offset={12} span={6} style={{float: 'right'}}>
                            <Button type="primary"
                                    onClick={() => this.handleSearchComplain()}
                            >
                                查询
                            </Button>
                            <Button type="default"
                                    onClick={() => this.handleReset()}
                                    style={{marginLeft: '10px'}}
                            >
                                重置
                            </Button>
                        </Col>
                    </Form>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };
};

const SearchLists = Form.create()(SearchList);
const CarManages = Form.create()(carManage);
export default prop => (
    <Consumer>
        {
            props => (
                <CarManages {...prop} {...props}/>
            )
        }
    </Consumer>
);